import json

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from Web.models import *

imagePath = 'http://284s49a651.zicp.vip/static/images/111.png'


# Create your views here.
# 登陆
#  post一个网址，附带一个包含”account”和”password”的json包
# 如果正确就返回一个json{state：ok,
# data:{nickname:String（该账号的昵称）
# imagePath:String
# }
# }
# 否则返回{state:fail}

def login(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        # print(data)
        account = data.get('account')
        password = data.get('password')
        res = AccountNumber.objects.filter(account=account).first()
        if res is None:
            fail = {"state": "fail"}
            print(fail)
            return JsonResponse(fail)
        elif res.password != password:
            fail = {"state": "fail"}
            print(fail)
            return JsonResponse(fail)
        else:
            right = {"state": "ok", "data": {"nickName": res.userName,
                                             "imagePath": imagePath}}
            # print(right)
            return JsonResponse(right)
    else:
        return JsonResponse({})


# check功能
# post一个网址，附带一个包含键”check”,”content”的json包
# 先检查check，如果check=checkPhoneNumber，则取出content，查找账号数据库中的是否有该电话号码，
# 如果有，返回的json包中state设置为1，如果没有state设置为0；
# 如果为checkAccount，则搜查账号，如果有state设置为1，如果没有state设置为0；
# 传回一个json{
# state:int(成功0，失败1)


def check(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        # print(data)
        check = data.get('check')
        if check == "checkPhoneNumber":
            content = data.get('content')
            result = AccountNumber.objects.filter(telephone=content).first()
            if result is None:
                print("0没查到")
                return JsonResponse({"state": 0})
            else:
                print("1查到了")
                return JsonResponse({"state": 1})
        if check == "checkAccount":
            content = data.get('content')
            result = AccountNumber.objects.filter(account=content).first()
            if result is None:
                return JsonResponse({"state": 0})
            else:
                return JsonResponse({"state": 1})
    else:
        return JsonResponse({})


# 注册功能
# post一个网址
# 则在账号数据库中新生成一个账号，图片路径设置为默认图片路径（在服务器上放置一张默认头像图片，新生成的账号图片路径都设为该图片路径，昵称设置为空）;
# 传入的json包
# {”phoneNumber”：…
# ,	”password”: …
# ,	”account”: …
# }


def register(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        phoneNumber = data.get('phoneNumber')
        password = data.get('password')
        account = data.get('account')
        if account is None:
            print("注册时的账号为空！")
            return JsonResponse({})
        elif len(account) == 0:
            print("注册时的账号为空！")
            return JsonResponse({})
        AccountNumber.objects.create(account=account, telephone=phoneNumber, password=password)
        return JsonResponse({})
    else:
        return JsonResponse({})


# 修改密码/昵称
# post一个网址
# 上传一个包含键”phoneNumber”，”password”,”nickName”,”account”的json包，必须对键的值进行判断，键的值可能为空，
# 根据phoneNumber/account找到数据，并将password/昵称重新设置
#
# if（phoneNumber键的value！=null）
# 找到数据
# else 用account的值找到数据
#
# if（password的值！=null）
# 修改新密码
# else 修改新昵称


def modifyNickname(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        print("data:", data)
        phoneNumber = data.get('phoneNumber')
        password = data.get('password')
        nickName = data.get('nickName')
        account = data.get('account')
        if password is None and nickName is None:
            return JsonResponse({})
        # AccountNumber.objects.create(account=account, telephone=phoneNumber, password=password)
        # 如果是空就
        if phoneNumber is None:
            ante = AccountNumber.objects.filter(account=account).first()
            if ante is None:
                print("账号不存在")
                return JsonResponse({"state": 0})
            elif password is not None:
                ante.password = password
                ante.save()
            else:
                ante.userName = nickName  #
                ante.save()
        else:
            anac = AccountNumber.objects.filter(telephone=phoneNumber).first()
            if anac is None:
                print("账号不存在")
                return JsonResponse({"state": 0})
            elif password is not None:
                anac.password = password
                anac.save()
            else:
                anac.userName = nickName
                anac.save()
        return JsonResponse({"state": 1})
    else:
        return JsonResponse({"state": 0})


# 删除评论
# 传入评论id{
# “commentId”: …
# }


def deletecomment(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        print("commentdata:", data)
        commentId = data.get('commentId')
        # print("commentId", commentId)
        com = CultureComment.objects.filter(id=commentId).first()
        if com is None:
            print("没有这条评论")
            return JsonResponse({"state": "fail"})
        else:
            com.delete()
            # com.save()
        return JsonResponse({"state": "ok"})
    else:
        return JsonResponse({"state": "ok"})


# 获得评论
# 传入文化/历史id{
# id：。。。
# type：。。。(两个值culture，和literary)
# }
# 搜索评论表找到结果，然后将结果转为Json包
# {
# {
# 		account：。。。。。用户账号
# 		comment：。。。用户评论
# 		commentId：。。。评论id
# 		date：。。。。。发布时间


def getcomment(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        fatherId = data.get('id')
        commenttype = data.get('type')
        # print("commenttype:", commenttype)
        # print("fatherId:", fatherId)
        if commenttype == 'literary':
            commentkind = AllBook.objects.filter(id=fatherId).first()
            com = Comment.objects.filter(bookName=commentkind).first()
            if com is None:
                print("没有这条评论")
                return JsonResponse({})
            else:
                account = com.account
                comment = com.commentContent
                commentId = commentkind
                commentdate = com.commenttime
            return JsonResponse(
                {"account": account, "comment": comment, "commentId": commentId, "commentdate": commentdate})
        elif commenttype == 'culture':
            cultureob = HistoryCulture.objects.filter(id=fatherId).first()  # 得到的文化对象
            if cultureob is None:
                print("没有这条文化对象")
            commSet = CultureComment.objects.filter(CultureOb=cultureob)  # 得到的所有评论的集合
            connlist = []
            if len(commSet) == 0:
                print("该朝代下没有评论")
                return JsonResponse({})
            else:
                for com in commSet:
                    account = com.account
                    comment = com.commentContent
                    commentId = com.id
                    commentdate = com.commenttime
                    connlist.append(
                        {"account": account, "comment": comment, "commentId": commentId,
                         "commentdate": str(commentdate.year) + "年" + str(commentdate.month) + "月" + str(
                             commentdate.day) +
                                        "日" + str(commentdate.hour) + "时" + str(commentdate.minute) + "分"})
                # print(type(connlist[0]["commentdate"]))
                # print(connlist)
                return JsonResponse({"data": connlist})

    else:
        return JsonResponse({})


# 上传评论
# 上传评论者账号、评论作品类型、文学作品/历史id、评论内容
# {
# 		account：。。。。。用户账号
# 		comment：。。。用户评论内容
# 		type：。。。评论类型
# 		id：。。。。。文学作品/历史id
# }
# 日期服务器端获取json包到达时间，id为自动生成


def uploadcomment(request):
    if request.method == 'POST':
        data = json.loads(request.body, )
        account = data.get('account')
        comment = data.get('comment')
        commenttype = data.get('type')
        fatherid = data.get('id')
        # 如果是文学作品的评论
        if commenttype == 'literary':
            bookob = AllBook.objects.filter(id=fatherid).first()  # 获取作品对象
            if bookob is None:  # 如果返回的作品对象是空
                return JsonResponse({})
            else:  # 如果返回的作品对象不是空，就在作品评论表里面插入评论
                Comment.objects.create(account=account, commentContent=comment, bookName=bookob)
                return JsonResponse({})
        # 如果是历史文化的评论
        elif commenttype == 'culture':
            cultureOb = HistoryCulture.objects.filter(id=fatherid).first()  # 获取历史文化对象
            if cultureOb is None:  # 如果返回的历史文化对象是空
                return JsonResponse({})
            else:  # 如果返回的历史文化对象不是空，就在历史文化评论表里面插入评论
                CultureComment.objects.create(account=account, commentContent=comment, CultureOb=cultureOb)
                return JsonResponse({"state": "ok"})
        else:
            return JsonResponse({"state": "ok"})
    else:
        return JsonResponse({})


# 获取历史文化数据
def gethistoryculture(request):
    hislist = HistoryCulture.objects.all()
    s = []
    returndata = {"type": "culture"}
    for i in hislist:
        s.append({"id": i.id, "summary": i.summury,
                  "dynasty": i.dynasty, "imagePath": imagePath})
    for j in s:
        if j["dynasty"] == "唐朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/唐朝.png"
        elif j["dynasty"] == "三皇五帝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/三皇五帝.png"
        elif j["dynasty"] == "宋朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/宋朝.png"
        elif j["dynasty"] == "周朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/周朝.png"
        elif j["dynasty"] == "夏朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/夏朝.png"
        elif j["dynasty"] == "秦朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/秦朝.png"
        elif j["dynasty"] == "汉朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/汉朝.png"
        elif j["dynasty"] == "三国":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/三国.png"
        elif j["dynasty"] == "晋朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/晋朝.png"
        elif j["dynasty"] == "南北朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/南北朝.png"
        elif j["dynasty"] == "隋朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/隋朝.png"
        elif j["dynasty"] == "五代":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/五代.png"
        elif j["dynasty"] == "元朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/元朝.png"
        elif j["dynasty"] == "明朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/明朝.png"
        elif j["dynasty"] == "清朝":
            j["imagePath"] = "http://284s49a651.zicp.vip/static/images/清朝.png"
    returndata["data"] = s
    content = json.dumps(returndata, ensure_ascii=False)
    response = HttpResponse(content, content_type='application/json; charset=utf-8')
    # print(returndata)
    return response


def getbook(request):  # 返回书的列表
    hislist = AllBook.objects.all().filter(checkBool=1)
    s = []
    returndata = {"type": "book"}
    for i in hislist:
        s.append({"id": i.id, "summary": i.bookContent, "author": i.author, "bookname": i.bookName,
                  "dynasty": i.dynasty, "imagePath": imagePath})
    returndata["data"] = s
    content = json.dumps(returndata, ensure_ascii=False)
    # print()
    response = HttpResponse(content, content_type='application/json; charset=utf-8')
    return response


def testpost(request):
    if request.method == 'POST':
        data = request.body
        data1 = json.loads(data)
        data2 = data1.get('name')
        print(type(data2))
        return HttpResponse("sadsad")
    else:
        return HttpResponse("方法不为post")
